package cn.csg.iotplatform.module.system.service.manufacturer;

import cn.csg.iotplatform.framework.web.core.util.WebFrameworkUtils;
import cn.csg.iotplatform.module.system.api.manufacturer.EqtManufacturerClient;
import cn.csg.iotplatform.module.system.api.manufacturer.dto.EqtDeleteManufactureDto;
import cn.csg.iotplatform.module.system.api.manufacturer.dto.EqtManufactureDto;
import cn.csg.iotplatform.module.system.api.file.dto.EqtFileDeleteVO;
import cn.csg.iotplatform.module.system.controller.admin.file.vo.EqtFileSaveVO;
import cn.csg.iotplatform.module.system.dal.dataobject.dvattachment.DvAttachmentDO;
import cn.csg.iotplatform.module.system.dal.dataobject.dvdeviceattachment.DvDeviceAttachmentDO;
import cn.csg.iotplatform.module.system.dal.dataobject.logger.GkDeviceCenterApiLogDO;
import cn.csg.iotplatform.module.system.dal.dataobject.user.AdminUserDO;
import cn.csg.iotplatform.module.system.dal.dataobject.userdept.UserDeptDO;
import cn.csg.iotplatform.module.system.dal.mysql.dvattachment.DvAttachmentMapper;
import cn.csg.iotplatform.module.system.dal.mysql.dvdeviceattachment.DvDeviceAttachmentMapper;
import cn.csg.iotplatform.module.system.enums.AttachmentTypeEnum;
import cn.csg.iotplatform.module.system.enums.DeviceCenterApiEnum;
import cn.csg.iotplatform.module.system.manufacturer.dto.ManufacturerRespDTO;
import cn.csg.iotplatform.module.system.service.eqfile.DvAttachmentService;
import cn.csg.iotplatform.module.system.service.eqfile.EqtFileService;
import cn.csg.iotplatform.module.system.service.logger.GkDeviceCenterApiLogService;
import cn.csg.iotplatform.module.system.service.user.AdminUserService;
import cn.csg.iotplatform.module.system.util.EqtCenterUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dtflys.forest.http.ForestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.csg.iotplatform.module.system.controller.admin.manufacturer.vo.*;
import cn.csg.iotplatform.module.system.dal.dataobject.manufacturer.ManufacturerDO;
import cn.csg.iotplatform.framework.common.pojo.PageResult;
import cn.csg.iotplatform.framework.common.util.object.BeanUtils;

import cn.csg.iotplatform.module.system.dal.mysql.manufacturer.ManufacturerMapper;

import static cn.csg.iotplatform.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csg.iotplatform.module.system.enums.ErrorCodeConstants.MANUFACTURER_HAS_EXISTS;

/**
 * 厂商信息 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
@Slf4j
public class ManufacturerServiceImpl implements ManufacturerService {

    @Resource
    private ManufacturerMapper manufacturerMapper;

    @Resource
    private EqtManufacturerClient eqtManufacturerClient;

    @Resource
    private DvDeviceAttachmentMapper dvDeviceAttachmentMapper;

    @Resource
    private EqtFileService eqtFileService;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private DvAttachmentMapper attachmentMapper;

    @Resource
    private DvAttachmentService dvAttachmentService;

    private static String configKey = "is_sync";

    @Value("${iot.eqt-center.bureauCode}")
    public String bureauCode;

    @Value("${iot.eqt-center.url}")
    public String gkUrl;

    @Resource
    private GkDeviceCenterApiLogService gkDeviceCenterApiLogService;

    @Override
    public String createManufacturer(ManufacturerSaveReqVO createReqVO) {

        validateManufacturerUnique(createReqVO);
        // 插入
        ManufacturerDO manufacturer = BeanUtils.toBean(createReqVO, ManufacturerDO.class);
        if(StrUtil.isBlank(createReqVO.getManufacturerId())) {
            manufacturer.setManufacturerId(IdUtil.fastSimpleUUID());
        }

        String value = manufacturerMapper.getGkConfig(configKey);
        if(StringUtils.isNotBlank(value) && value.equals("1")) {
            log.info("同步共库中心新增: {}", createReqVO);

            EqtManufactureDto vendorVO = buildEqtManufacture(manufacturer, "insert");
            JSONObject response = syncManufactureData(vendorVO);
            String id = response.getString("data");
            manufacturer.setId(id);

            try{
                syncInsertFile(manufacturer);
            } catch (Exception e) {
                syncWlFile(manufacturer, 1);
                throw exception(e.getMessage());
            }
            syncWlFile(manufacturer, 0);
        } else {
            manufacturer.setId(IdUtil.fastSimpleUUID());
            manufacturer.setIsSync(0);
            manufacturerMapper.insert(manufacturer);
        }

        // 返回
        return manufacturer.getId();
    }

    /**
     *
     * @param manufacturer
     *
     * 附件备份到物联本地
     */
    private void syncWlFile(ManufacturerDO manufacturer, Integer type) {
        try {
            attachmentMapper.deleteByFlagId(manufacturer.getId());
            // 营业执照图片同步
            if(StringUtils.isNotBlank(manufacturer.getBusinessUrl())) {
                // 获取物联minio的url地址
                String url = getUrl(manufacturer, manufacturer.getBusinessUrl(), AttachmentTypeEnum.businessUrl.name());
                dvAttachmentService.syncWlFile(manufacturer.getId(), AttachmentTypeEnum.businessUrl.name(), url, null, type);
            }

            // 公司logo图片同步
            if(StringUtils.isNotBlank(manufacturer.getLogo())) {
                String url = getUrl(manufacturer, manufacturer.getLogo(), AttachmentTypeEnum.logo.name());
                dvAttachmentService.syncWlFile(manufacturer.getId(), AttachmentTypeEnum.logo.name(), url, null, type);
            }

            // 证书图片同步
            if(CollectionUtils.isNotEmpty(manufacturer.getCertificates())) {
                for(Map<String,Object> map : manufacturer.getCertificates()) {
                    if(map != null && !map.isEmpty()) {
                        String url = getUrl(manufacturer, map.get("filePath") != null ?  map.get("filePath").toString() : null, AttachmentTypeEnum.certificatesImage.name());
                        dvAttachmentService.syncWlFile(manufacturer.getId(), AttachmentTypeEnum.certificatesImage.name(), url, map, type);
                    }
                }
            }
        } catch (Exception e) {
            log.error("附件备份数据失败: {}", e);
        }

    }

    private String getUrl(ManufacturerDO manufacturer, String filePath, String type) {
        if(StringUtils.isEmpty(filePath)) {
            return null;
        }
        DvDeviceAttachmentDO deviceAttachmentDO = dvDeviceAttachmentMapper.getAttachment(manufacturer.getId(), filePath, type);
        String url = null;
        if(deviceAttachmentDO != null) {
            url = deviceAttachmentDO.getIotUrl();
        } else if(!filePath.contains(gkUrl)) {
            url = filePath;
        }
        return url;
    }


    @Override
    public void updateManufacturer(ManufacturerSaveReqVO updateReqVO) {
        validateManufacturerUnique(updateReqVO);
        // 更新
        ManufacturerDO manufacturer = BeanUtils.toBean(updateReqVO, ManufacturerDO.class);

        String value = manufacturerMapper.getGkConfig(configKey);
        if(StringUtils.isNotBlank(value) && value.equals("1")) {
            log.info("同步共库中心修改: {}", updateReqVO);
            EqtManufactureDto vendorVO = buildEqtManufacture(manufacturer, "update");
            syncManufactureData(vendorVO);
            try{
                syncUpdateFile(manufacturer);
            } catch (Exception e) {
                syncWlFile(manufacturer, 1);
                throw exception(e.getMessage());
            }
            syncWlFile(manufacturer, 0);
        } else {
            manufacturerMapper.updateById(manufacturer);
        }

    }

    @Override
    public void deleteManufacturer(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        // 判断厂商是否被使用
        List<String> list = manufacturerMapper.getAuthManu(idList);
        if(CollectionUtils.isNotEmpty(list)) {
            throw exception("存在被使用厂商，请重新选择");
        }
        String value = manufacturerMapper.getGkConfig(configKey);
        if(StringUtils.isNotBlank(value) && value.equals("1")) {
            log.info("同步共库中心删除{}", ids);
            for(String id : idList) {
                EqtDeleteManufactureDto dto = EqtDeleteManufactureDto.builder().vendorId(id).bureauCode(bureauCode).build();
                syncDeleteManufacturer(dto);
            }
        } else {
            //分批删除
            int batchSize = 100;
            int total = idList.size();
            int count = 0;
            while (count < total) {
                int endIndex = Math.min(count + batchSize, total);
                List<String> subList = idList.subList(count, endIndex);
                manufacturerMapper.deleteBatchIds(subList);
                count += batchSize;
            }
        }

    }

    private EqtManufactureDto buildEqtManufacture(ManufacturerDO manufacturerDO, String type) {
        Long userId = WebFrameworkUtils.getLoginUserId();
        log.info("当前登录人: {}", userId);

        EqtManufactureDto vendorVO = BeanUtils.toBean(manufacturerDO, EqtManufactureDto.class);
        vendorVO.setVendorCode(manufacturerDO.getUnifiedSocialCreditCode());
        vendorVO.setVendorName(manufacturerDO.getManufacturerName());
        vendorVO.setVendorShortName(manufacturerDO.getManufacturerShortName());
        vendorVO.setContactMan(manufacturerDO.getManufacturerUser());
        vendorVO.setTelephone(manufacturerDO.getManufacturerTel());
        vendorVO.setWebSite(manufacturerDO.getManufacturerUrl());
        vendorVO.setRemark(manufacturerDO.getNote());
        vendorVO.setEmail(manufacturerDO.getContactEmail());
        // vendorVO.setRegion(manufacturerDO.getManufacturerAddressDetail());
        vendorVO.setManufacturerCode(manufacturerDO.getManufacturerId());
        vendorVO.setBureauCode(bureauCode);
        vendorVO.setAddress(manufacturerDO.getManufacturerAddressDetail());
        if(type != null && type.equals("insert")) {
            vendorVO.setCreator(userId != null ? userId + "" : null);
        }
        vendorVO.setUpdater(userId != null ? userId + "" : null);
        return vendorVO;
    }

    @Override
    public JSONObject syncManufactureData(EqtManufactureDto vendorVO){
        // 标准厂商进行一次同步任务
        log.info("同步共库中心: {}", vendorVO);

        //插入日志
        GkDeviceCenterApiLogDO gkDeviceCenterApiLogDO = new GkDeviceCenterApiLogDO();
        gkDeviceCenterApiLogDO.setRequestParam( JSONObject.toJSONString( vendorVO ) );

        ForestResponse<JSONObject> response = eqtManufacturerClient.insertEqtManufacturer(EqtCenterUtil.doPostJsonHeader(JSON.toJSONString(vendorVO)), vendorVO);
        log.info("厂商同步共库返回信息{},{}, {}", response.getException(), response.getContent(), response.getResult());
        if ( !response.isSuccess() || (response.getResult().get("code") != null && !response.getResult().get("code").toString().equals("200")) ){
            if(!response.isSuccess()) {
                gkDeviceCenterApiLogDO.setStatusCode( response.statusCode() + "" );
                gkDeviceCenterApiLogDO.setResponseResult( response.getResult() + "" );
                gkDeviceCenterApiLogService.createLog( gkDeviceCenterApiLogDO, DeviceCenterApiEnum.INSERTEQTMANUFACTURER );
                throw exception("厂商同步共库失败" + response.getResult());
            }
            String msg = "";
            log.error("厂商同步共库异常信息: {}", response.getResult());
            if(response.getResult() != null && response.getResult().get("msg") != null) {
                msg =  response.getResult().get("msg").toString();
            }
            gkDeviceCenterApiLogDO.setStatusCode( response.getResult().get("code") + "" );
            gkDeviceCenterApiLogDO.setResponseResult( msg );
            gkDeviceCenterApiLogService.createLog( gkDeviceCenterApiLogDO, DeviceCenterApiEnum.INSERTEQTMANUFACTURER );
            throw exception("厂商同步共库失败" + msg);
        }
        gkDeviceCenterApiLogDO.setStatusCode( response.statusCode() + "" );
        gkDeviceCenterApiLogDO.setResponseResult( response.getResult() + "" );
        gkDeviceCenterApiLogService.createLog( gkDeviceCenterApiLogDO, DeviceCenterApiEnum.INSERTEQTMANUFACTURER );
        return response.getResult();
    }

    private void syncDeleteManufacturer(EqtDeleteManufactureDto dto){
        // 标准厂商进行一次同步任务
        log.info("同步共库中心删除: {}", dto);

        //插入日志
        GkDeviceCenterApiLogDO gkDeviceCenterApiLogDO = new GkDeviceCenterApiLogDO();
        gkDeviceCenterApiLogDO.setRequestParam( JSONObject.toJSONString( dto ) );

        ForestResponse<JSONObject> response = eqtManufacturerClient.deleteEqtManufacturer(EqtCenterUtil.doPostJsonHeader(JSON.toJSONString(dto)), dto);
        log.info("厂商同步删除共库返回信息{},{}, {}", response.getException(), response.getContent(), response.getResult());
        if ( !response.isSuccess() || (response.getResult().get("code") != null && !response.getResult().get("code").toString().equals("200")) ){
            if(!response.isSuccess()) {
                gkDeviceCenterApiLogDO.setStatusCode( response.statusCode() + "" );
                gkDeviceCenterApiLogDO.setResponseResult( response.getResult() + "" );
                gkDeviceCenterApiLogService.createLog( gkDeviceCenterApiLogDO, DeviceCenterApiEnum.DELETEEQTMANUFACTURER );
                throw exception("厂商同步共库删除失败" + response.getResult());
            }
            String msg = "";
            if(response.getResult() != null && response.getResult().get("msg") != null) {
                msg =  response.getResult().get("msg").toString();
            }
            gkDeviceCenterApiLogDO.setStatusCode( response.getResult().get("code") + "" );
            gkDeviceCenterApiLogDO.setResponseResult( msg );
            gkDeviceCenterApiLogService.createLog( gkDeviceCenterApiLogDO, DeviceCenterApiEnum.DELETEEQTMANUFACTURER );
            throw exception("厂商同步共库失败" + msg);
        }

        gkDeviceCenterApiLogDO.setStatusCode( response.statusCode() + "" );
        gkDeviceCenterApiLogDO.setResponseResult( response.getResult() + "" );
        gkDeviceCenterApiLogService.createLog( gkDeviceCenterApiLogDO, DeviceCenterApiEnum.DELETEEQTMANUFACTURER );
    }

    private void syncInsertFile(ManufacturerDO manufacturer) {
        // 营业执照图片同步
        if(StringUtils.isNotBlank(manufacturer.getBusinessUrl())) {
            syncFile(manufacturer, AttachmentTypeEnum.businessUrl.name(), manufacturer.getBusinessUrl(), null);
        }

        // 公司logo图片同步
        if(StringUtils.isNotBlank(manufacturer.getLogo())) {
            syncFile(manufacturer, AttachmentTypeEnum.logo.name(), manufacturer.getLogo(), null);

        }

        // 证书图片同步
        if(CollectionUtils.isNotEmpty(manufacturer.getCertificates())) {
            for(Map<String,Object> map : manufacturer.getCertificates()) {
                if(map != null && !map.isEmpty()) {
                    syncFile(manufacturer, AttachmentTypeEnum.certificatesImage.name(), null, map);
                }
            }
        }
    }

    private void syncUpdateFile(ManufacturerDO manufacturer) {
        // 营业执照图片同步修改
        if(StringUtils.isNotBlank(manufacturer.getBusinessUrl())) {
            List<DvDeviceAttachmentDO> attachmentDOList = dvDeviceAttachmentMapper.getAttachments(manufacturer.getId(), AttachmentTypeEnum.businessUrl.name());
            if(CollectionUtils.isNotEmpty(attachmentDOList)) {
                String attachmentFullPath = attachmentDOList.get(0).getAttachmentFullPath();
                if(attachmentFullPath == null || !attachmentFullPath.equals(manufacturer.getBusinessUrl())) {
                    syncFile(manufacturer, AttachmentTypeEnum.businessUrl.name(), manufacturer.getBusinessUrl(), null);
                }
            } else {
                syncFile(manufacturer, AttachmentTypeEnum.businessUrl.name(), manufacturer.getBusinessUrl(), null);
            }
        }

        // 公司logo图片同步修改
        if(StringUtils.isNotBlank(manufacturer.getLogo())) {
            List<DvDeviceAttachmentDO> attachmentDOList = dvDeviceAttachmentMapper.getAttachments(manufacturer.getId(), AttachmentTypeEnum.logo.name());
            if(CollectionUtils.isNotEmpty(attachmentDOList)) {
                String attachmentFullPath = attachmentDOList.get(0).getAttachmentFullPath();
                if(attachmentFullPath == null || !attachmentFullPath.equals(manufacturer.getLogo())) {
                    syncFile(manufacturer, AttachmentTypeEnum.logo.name(), manufacturer.getLogo(), null);
                }
            } else {
                syncFile(manufacturer, AttachmentTypeEnum.logo.name(), manufacturer.getLogo(), null);
            }
        }

        // 证书图片同步修改
        // 记录表已有的证书id
        List<String> attachmentIds = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(manufacturer.getCertificates())) {
            for(Map<String,Object> map : manufacturer.getCertificates()) {
                // 新增的证书同步
                if(map != null && !map.isEmpty()) {
                    if(!map.containsKey("id")) {
                        syncFile(manufacturer, AttachmentTypeEnum.certificatesImage.name(), null, map);
                    } else {
                        attachmentIds.add(map.get("id").toString());
                    }
                }
            }
            List<DvDeviceAttachmentDO> attachmentDOList = dvDeviceAttachmentMapper.getDeleteAttachments(attachmentIds, manufacturer.getId());
            if(CollectionUtils.isNotEmpty(attachmentDOList)) {
                // 删除多余证书
                for(DvDeviceAttachmentDO attachmentDO : attachmentDOList) {
                    syncDeleteFile(attachmentDO, AttachmentTypeEnum.certificatesImage.name());
                }
            }
        } else {
            // 删除多余证书
            List<DvDeviceAttachmentDO> attachmentDOList = dvDeviceAttachmentMapper.getDeleteAttachments(attachmentIds, manufacturer.getId());
            if(CollectionUtils.isNotEmpty(attachmentDOList)) {

                for(DvDeviceAttachmentDO attachmentDO : attachmentDOList) {
                    syncDeleteFile(attachmentDO, AttachmentTypeEnum.certificatesImage.name());
                }
            }
        }
    }

    private void syncFile(ManufacturerDO manufacturer, String jobTypeCode, String url, Map<String,Object> map) {
        EqtFileSaveVO eqtFileSaveVO = new EqtFileSaveVO();
        eqtFileSaveVO.setObjectId(manufacturer.getId());
        eqtFileSaveVO.setFlag("1");
        eqtFileSaveVO.setJobTypeCode(jobTypeCode);
        eqtFileSaveVO.setFileUrl(url);

        if(jobTypeCode.equals(AttachmentTypeEnum.certificatesImage.name())) {
            eqtFileSaveVO.setCertificatesType(map.get("certificate") != null && StringUtils.isNotBlank(map.get("certificate").toString())?
                    map.get("certificate").toString() : null);
            eqtFileSaveVO.setCertificatesLevel(map.get("levelOrType") != null && StringUtils.isNotBlank(map.get("levelOrType").toString()) ?
                    Integer.parseInt(map.get("levelOrType").toString()) : null);
            eqtFileSaveVO.setCertificatesCode(map.get("certificateNo") != null ?
                    map.get("certificateNo").toString() : null);
            eqtFileSaveVO.setFileUrl(map.get("filePath") != null ?
                    map.get("filePath").toString() : null);
        }
        eqtFileService.syncFile(eqtFileSaveVO);
    }

    private void syncDeleteFile(DvDeviceAttachmentDO attachmentDO, String jobTypeCode) {

        EqtFileDeleteVO eqtFileDeleteVO = new EqtFileDeleteVO();
        eqtFileDeleteVO.setObjectId(attachmentDO.getFlagId());
        eqtFileDeleteVO.setAttachmentId(attachmentDO.getAttachmentId());
        eqtFileDeleteVO.setJobTypeCode(jobTypeCode);
        eqtFileService.syncDeleteFile(eqtFileDeleteVO);
    }

    private void validateManufacturerUnique(ManufacturerSaveReqVO reqVO) {
        LambdaQueryWrapper<ManufacturerDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ManufacturerDO::getManufacturerId,reqVO.getManufacturerId());
//        queryWrapper.eq(ManufacturerDO::getManufacturerName,reqVO.getManufacturerName());
        if(reqVO.getId() != null){
            queryWrapper.ne(ManufacturerDO::getId,reqVO.getId());
        }
        if(manufacturerMapper.selectCount(queryWrapper) > 0)  throw exception(MANUFACTURER_HAS_EXISTS);

        //add by zhangjinpeng 2024-10-22 添加判断：厂商名称或者厂商编码未对系统唯一性进行校验
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ManufacturerDO::getManufacturerName,reqVO.getManufacturerName());
        if(reqVO.getId() != null){
            queryWrapper.ne(ManufacturerDO::getId,reqVO.getId());
        }
        if(manufacturerMapper.selectCount(queryWrapper) > 0)  throw exception(MANUFACTURER_HAS_EXISTS);
    }
    @Override
    public ManufacturerVO getManufacturerDetail(String id) {
        ManufacturerVO manufacturerVO = getManufacturer(id);
        getWlFileAttachment(manufacturerVO);
        return manufacturerVO;
    }

    @Override
    public ManufacturerVO getManufacturer(String id) {
        List<Map<String,Object>> certificates = new ArrayList<>();
        ManufacturerDO manufacturer = manufacturerMapper.selectById(id);
        ManufacturerVO manufacturerVO = BeanUtils.toBean(manufacturer, ManufacturerVO.class);
        // 设置图片来源共库中心
        manufacturerVO.setBusinessSource(2);
        manufacturerVO.setLogoSource(2);
        manufacturerVO.setCertificatesSource(2);
        manufacturerVO.setManufacturerAddress(manufacturerVO.getProvince() + "-" + manufacturerVO.getCity() + "-" + manufacturerVO.getArea());
        List<DvDeviceAttachmentDO> attachmentDOList = dvDeviceAttachmentMapper.getAttachmentByManuId(id);
        String value = manufacturerMapper.getGkConfig(configKey);
        if(StringUtils.isNotBlank(value) && value.equals("1")) {
            if(CollectionUtils.isNotEmpty(attachmentDOList)) {
                for(DvDeviceAttachmentDO attachmentDO : attachmentDOList) {
                    if(attachmentDO.getJobTypeCode().equals(AttachmentTypeEnum.businessUrl.name())) {
                        manufacturerVO.setBusinessUrl(attachmentDO.getAttachmentFullPath());
                        manufacturerVO.setBusinessSource(1);
                    } else if(attachmentDO.getJobTypeCode().equals(AttachmentTypeEnum.logo.name())) {
                        manufacturerVO.setLogo(attachmentDO.getAttachmentFullPath());
                        manufacturerVO.setLogoSource(1);
                    } else if(attachmentDO.getJobTypeCode().equals(AttachmentTypeEnum.certificatesImage.name())) {
                        Map<String,Object> map = new HashMap<>(16);
                        map.put("id", attachmentDO.getId());
                        map.put("filePath", attachmentDO.getAttachmentFullPath());
                        map.put("certificate", attachmentDO.getCertificatesType());
                        map.put("levelOrType", attachmentDO.getCertificatesLevel());
                        map.put("certificateNo", attachmentDO.getCertificatesCode());
                        certificates.add(map);
                        manufacturerVO.setCertificatesSource(1);
                    }
                }
                manufacturerVO.setCertificates(certificates);
            }
        }
        return manufacturerVO;
    }

    private void getWlFileAttachment(ManufacturerVO manufacturerVO) {
        List<Map<String,Object>> certificates = new ArrayList<>();
        List<DvAttachmentDO> list;

        if(StringUtils.isEmpty(manufacturerVO.getBusinessUrl())) {
            list = attachmentMapper.getAttachment(manufacturerVO.getId(), AttachmentTypeEnum.businessUrl.name());
            if(CollectionUtils.isNotEmpty(list)) {
                manufacturerVO.setBusinessUrl(list.get(0).getAttachmentFullPath());
                manufacturerVO.setBusinessSource(2);
            }
        }
        if(StringUtils.isEmpty(manufacturerVO.getLogo())) {
            list = attachmentMapper.getAttachment(manufacturerVO.getId(), AttachmentTypeEnum.logo.name());
            if(CollectionUtils.isNotEmpty(list)) {
                manufacturerVO.setLogo(list.get(0).getAttachmentFullPath());
                manufacturerVO.setLogoSource(2);
            }
        }
        if(CollectionUtils.isEmpty(manufacturerVO.getCertificates())) {
            list = attachmentMapper.getAttachment(manufacturerVO.getId(), AttachmentTypeEnum.certificatesImage.name());
            if(CollectionUtils.isNotEmpty(list)) {
                for(DvAttachmentDO attachmentDO : list) {
                    Map<String,Object> map = new HashMap<>(16);
                    map.put("id", attachmentDO.getId());
                    map.put("filePath", attachmentDO.getAttachmentFullPath());
                    map.put("certificate", attachmentDO.getCertificatesType());
                    map.put("levelOrType", attachmentDO.getCertificatesLevel());
                    map.put("certificateNo", attachmentDO.getCertificatesCode());
                    certificates.add(map);
                }
                manufacturerVO.setCertificates(certificates);
                manufacturerVO.setCertificatesSource(2);
            }
        }
    }

    @Override
    public PageResult<ManufacturerDO> getManufacturerPage(ManufacturerPageReqVO pageReqVO) {
        PageResult<ManufacturerDO> result = manufacturerMapper.selectPage(pageReqVO);
        if(result.getTotal() > 0) {
            for(ManufacturerDO manufacturerDO : result.getList()) {
                manufacturerDO.setManufacturerAddress((manufacturerDO.getProvince() != null ? manufacturerDO.getProvince() : "") + "-"
                        + (manufacturerDO.getCity() != null ? manufacturerDO.getCity() : "")  + "-"
                        + (manufacturerDO.getArea() != null ? manufacturerDO.getArea() : "")
                );
            }
        }
        return result;
    }

    @Override
    public ManufacturerDO getDeviceManufacturerByName(String name) {
        return manufacturerMapper.selectOne(ManufacturerDO::getManufacturerName,name);
    }

    @Override
    public ManufacturerUniqueRespVO checkUnique(ManufacturerUniqueReqVO reqVO) {
        ManufacturerUniqueRespVO respVO = ManufacturerUniqueRespVO.builder().build();
        respVO.setManufacturerIdCount(manufacturerMapper.selectCount(ManufacturerDO::getManufacturerId,reqVO.getManufacturerId()));
        respVO.setManufacturerNoCount(manufacturerMapper.selectCount(ManufacturerDO::getManufacturerNo,reqVO.getManufacturerNo()));
        respVO.setManufacturerNameCount(manufacturerMapper.selectCount(ManufacturerDO::getManufacturerName,reqVO.getManufacturerName()));
        return respVO;
    }

    @Override
    public List<ManufacturerDO> getConstructionManufacturerList() {
        LambdaQueryWrapper<ManufacturerDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ManufacturerDO::getManufacturerType,"2");
        return manufacturerMapper.selectList(queryWrapper);
    }

    @Override
    public ManufacturerDO getDeviceManufacturerByNameAndType(String name, String type) {
        LambdaQueryWrapper<ManufacturerDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ManufacturerDO::getManufacturerType,"2");
        queryWrapper.eq(ManufacturerDO::getManufacturerName,name);
        queryWrapper.last(" limit 1");
        return manufacturerMapper.selectOne(queryWrapper);
    }


    @Override
    public List<ManufacturerRespDTO> getDeviceManufacturer() {
        LambdaQueryWrapper<ManufacturerDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq( ManufacturerDO::getDeleted, 0 );
        List<ManufacturerDO> manufacturerDOS = manufacturerMapper.selectList();
        return BeanUtils.toBean( manufacturerDOS, ManufacturerRespDTO.class );
    }

    @Override
    public void syncManufacturerList() {
        List<ManufacturerDO> list = manufacturerMapper.getSyncManufacturerList();
        for(ManufacturerDO manufacturerDO : list) {
            try {
                syncInsertFile(manufacturerDO);
                syncWlFile(manufacturerDO, 0);
                manufacturerMapper.updateManufacturerSyncStatus(manufacturerDO.getId());
            } catch (Exception e) {
                 log.error("上传附件失败：{}, {}, {}", manufacturerDO.getId(), manufacturerDO.getManufacturerName(), e);
            }
        }
        log.info("同步厂商附件完成");
    }

}